var district, polygons=[], citycode;
function mapInit(){
  var mapObj;
  var citySelect = document.querySelector('#city');
  var districtSelect = document.querySelector('#district');
  mapObj = new AMap.Map('iCenter',{
    rotateEnable:true,
    dragEnable:true,
    zoomEnable:true,
    zooms:[3,18],
    layers: [
        new AMap.TileLayer()
    ],
    view: new AMap.View2D({
        center: new AMap.LngLat(116.30946,39.937629),
        zoom: 4
    })
});
 mapObj.plugin(["AMap.Scale"],function(){
      scale = new AMap.Scale();
      mapObj.addControl(scale);
  });
var provinceList = ['北京市', '天津市', '河北省', '山西省', '内蒙古自治区', '辽宁省', '吉林省','黑龙江省', '上海市', '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省','河南省', '湖北省', '湖南省', '广东省', '广西壮族自治区', '海南省', '重庆市','四川省', '贵州省', '云南省', '西藏自治区', '陕西省', '甘肃省', '青海省', '宁夏回族自治区', '新疆维吾尔自治区', '台灣', '香港特别行政区', '澳门特别行政区'];
var provinceSelect = document.querySelector('#province');
var content = '<option>--请选择--</option>';
for(var i =0, l = provinceList.length; i<l; i++){
  content += '<option value="province">'+provinceList[i]+'</option>';
  provinceSelect.innerHTML = content;
}
//行政区划查询
mapObj.plugin(["AMap.DistrictSearch"], function() {
    var opts = {
        subdistrict: 1,   //返回下一级行政区
        extensions: 'all',  //返回行政区边界坐标组等具体信息
        level:'city'  //查询行政级别为 市
    };

    //实例化DistrictSearch
    district = new AMap.DistrictSearch(opts);

    //查询成功时的回调函数，定义如何展示请求返回结果
    AMap.event.addListener(district, 'complete', function(e){
      var dList = e.districtList;
      for(var m = 0,ml = dList.length; m < ml; m++){
        var data = e.districtList[m].level;
        var bounds = e.districtList[m].boundaries;

        if(data == "district" && dList[m].citycode === citycode){//只绘制 区, 且 本级别行政区划是上一级区划的下级行政区
          if(bounds) {
            for(var i =0, l = bounds.length; i < l; i++){
              //生成行政区划polygon
              var polygon = new AMap.Polygon({
                map:mapObj,
                strokeWeight:2,
                // strokeColor:'#CC66CC',
                // fillColor:'#CCF3FF',
                fillOpacity:0,
                path:bounds[i]
              });
              polygons.push(polygon);
            }
            mapObj.setFitView();//地图自适应
            if(polygon != 'undefined') {polygon.setMap(null);}
          }
        }

        var list = e.districtList || [],
            subList =[], level, nextLevel;
        if(list.length >= 1) {
          subList = list[0].districtList;
          level = list[0].level;
        }

        //清空下一级别的下拉列表
        if(level === 'province'){
          nextLevel = 'city';
          citySelect.innerHTML = '';
          districtSelect.innerHTML = '';
        }else if(level === 'city'){
          nextLevel = 'district';
          districtSelect.innerHTML = '';
        }
        if(subList){
          var contentSub = '<option>--请选择--</option>';
          for(var i=0,l=subList.length; i<l; i++){
            var name = subList[i].name;
            var levelSub = subList[i].level;
            var cityCode = subList[i].citycode;
            contentSub += '<option value="'+levelSub+'|'+cityCode+'">'+name+'</option>';
            document.querySelector('#'+levelSub).innerHTML = contentSub;
          }
        }
      }
    });
var startPoint, endPoint, lineId= 1, incDistanceFlag = 1;
var clickEventListener=AMap.event.addListener(mapObj,'click',function(e){
        clicklnglat = e.lnglat;
        pointSet = $("#clickPoint").val();
        if(pointSet != '')
        {
          pointSet = pointSet + '|';
          endPoint = clicklnglat;
        }
        else{
          startPoint = clicklnglat;
          endPoint = clicklnglat;
        }
        var stepDistance = 0;
        if (incDistanceFlag == 1) {
            distance = $("#distance").val();
            stepDistance = endPoint.distance(startPoint) / 1000;
            stepDistance = stepDistance.toFixed(2);
            distance = parseFloat(distance) + parseFloat(stepDistance);
            $("#distance").val(distance.toFixed(2));
        } else {
            incDistanceFlag = 1;
        }

        $("#clickPoint").val(pointSet+ clicklnglat.getLng() +',' + clicklnglat.getLat() +','+ stepDistance +','+lineId);
        startPoint = clicklnglat;
      });
var clickEventListener=AMap.event.addListener(mapObj,'rightclick',function(e){
    incDistanceFlag = 0;
    lineId++;
});
  mapObj.plugin(["AMap.RangingTool"],function(){
     var sMarker = {
            icon:new AMap.Icon({    //复杂图标
            size:new AMap.Size(28,37),//图标大小
            image:"http://webapi.amap.com/images/custom_a_j.png", //大图地址
            imageOffset:new AMap.Pixel(0,0)//相对于大图的取图位置
        })
    };
    var eMarker = {
            icon:new AMap.Icon({    //复杂图标
                size:new AMap.Size(28,37),//图标大小
                image:"http://webapi.amap.com/images/custom_a_j.png", //大图地址
                imageOffset:new AMap.Pixel(-28,0)//相对于大图的取图位置
            }),
            offset: new AMap.Pixel(-16,-35)
    };
    var lOptions={ 
            strokeStyle:"solid",
            strokeColor:"#FF33FF",
            strokeOpacity:1,
            strokeWeight:2
    };
    var rulerOptions = {startMarkerOptions:sMarker,endMarkerOptions:eMarker,lineOptions:lOptions};
    ruler = new AMap.RangingTool(mapObj,rulerOptions);
    ruler.turnOn();
});
});

return mapObj;
}
function search(obj){
  // 清除地图上所有覆盖物
  for(var i = 0, l = polygons.length; i< l; i ++){
    polygons[i].setMap(null);
  }
  var option = obj[obj.options.selectedIndex];
  var arrTemp = option.value.split('|');
  var level = arrTemp[0];//行政级别
  citycode = arrTemp[1];// 城市编码
  var keyword = option.text; //关键字

  district.setLevel(level); //行政区级别
  district.search(keyword); //行政区查询
}
